import React, { Component } from 'react';
import { connect } from 'react-redux';
import { HashRouter as Router, Route } from 'react-router-dom';
import { Layout, Menu, Breadcrumb, Dropdown, Modal, Tag, Icon, Tooltip } from 'antd';
import axios from '../axios.config';
import JavascriptCommon from '../javascript.common';
const { SubMenu } = Menu;
const { Header, Content, Sider } = Layout;


class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsed: false,
            currentMenu: {},
            breadcrumbs: []
        };
    }
    componentDidMount() {
        if (sessionStorage.getItem("session_history")) {
            this.props.dispatch({
                type: "SET_HISTORYROUTE",
                payload: JSON.parse(sessionStorage.getItem("session_history"))
            });
        }
        setTimeout(() => {
            this.onhashchange();
            if ("onhashchange" in window) {
                window.addEventListener("hashchange", () => { this.onhashchange(); }, false);
            }
        }, 200);
    }
    onhashchange() {
        let route = {};
        let is404 = true;
        let hash = window.location.hash.replace(/^#/, "");
        if (/^\/$/g.test(hash) && this.props.source.length > 0) {
            hash = this.props.source[0].path;
            this.props.source.forEach(({ path }) => { if (path === "/main") { hash = path; } });
            window.location.hash = hash;
            return true;
        }
        this.props.source.forEach(item => { if (item.path === hash) { is404 = false; route = item; } });
        if (is404) { window.location.hash = "/error"; return true; }

        this.buildCrumb(this.props.routes, [], hash);
        this.props.source.forEach(item => {
            if (item.path === hash) {
                this.setState({ currentMenu: item });
            }
        });
        if (route) { this.handlerhistory(route) };
    }
    buildCrumb(routes, breadcrumbs, hash) {
        routes.forEach((item, index) => {
            if (item.leaf) {
                if (item.path === hash) {
                    breadcrumbs.push(item.name);
                    this.setState({
                        breadcrumbs: JSON.parse(JSON.stringify(breadcrumbs))
                    });
                } else {
                    if (routes.length <= 1 || index === routes.length - 1) {
                        breadcrumbs.splice(0, breadcrumbs.length);
                    }
                }
            } else {
                if (item.children.length > 0) {
                    breadcrumbs.push(item.name);
                    this.buildCrumb(item.children, breadcrumbs, hash);
                }
            }
        });
    }
    menuCLick(menu) {
        window.location.hash = menu.item.props.path;
    }
    handlerhistory(route) {
        let history = JSON.parse(JSON.stringify(this.props.historyroute));
        history.forEach((item, index) => {
            if (item.name === route.name) {
                history.splice(index, 1);
            }
        });
        history.push({ name: route.name, path: route.path });
        if (history.length > 5) { history.splice(0, 1); }
        sessionStorage.setItem("session_history", JSON.stringify(history));
        this.props.dispatch({ type: "SET_HISTORYROUTE", payload: history });
    }
    spliceTag(index) {
        let history = JSON.parse(JSON.stringify(this.props.historyroute));
        history.splice(index, 1);
        sessionStorage.setItem("session_history", JSON.stringify(history));
        this.props.dispatch({ type: "SET_HISTORYROUTE", payload: history });
    }
    clickTag(target, path, index) {
        if (target.tagName.toLowerCase() === "div" && this.props.historyroute.length !== index + 1) {
            window.location.hash = path;
        }
    }
    logout() {
        Modal.confirm({
            title: "提示",
            content: "确定要退出本系统?",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                axios.post("Http/Msg/MsgStart.ashx?method=Backend_Logout").then(res => {
                    sessionStorage.clear();
                    window.location.replace("/");
                });
            },
        });
    }
    render() {
        let createMemu = () => {
            if (this.state.currentMenu.index) {
                if (this.state.collapsed) {
                    return <Menu mode="inline" style={{ height: '100%' }} selectedKeys={[this.state.currentMenu.index]}>
                        {this.props.routes.map(item => {
                            if (!item.hidden) {
                                return <Menu.Item key={item.index} path={item.path} onClick={() => { this.setState({ collapsed: !this.state.collapsed }); }} >
                                    <Tooltip title={item.name} placement="right">
                                        <i className={item.iconCls}></i>
                                    </Tooltip>
                                </Menu.Item >;
                            }
                        })}
                    </Menu>;
                } else {
                    return <Menu mode="inline" style={{ height: '100%' }} onClick={m => { this.menuCLick(m); }}
                        selectedKeys={[this.state.currentMenu.index]} defaultOpenKeys={[this.state.currentMenu.parent]}
                    >
                        {this.props.routes.map(item => (buildMenu(item)))}
                    </Menu>
                }
            }
        };
        let buildMenu = (item) => {
            if (!item.hidden) {
                if (item.leaf) {
                    return <Menu.Item key={item.index} path={item.path}><i className={item.iconCls} style={{ marginRight: "8px" }}></i>{item.name}</Menu.Item >
                } else {
                    return <SubMenu key={item.index} title={<span><i className={item.iconCls} style={{ marginRight: "8px" }}></i>{item.name}</span>}>
                        {item.children.map(child => (buildMenu(child)))}
                    </SubMenu>
                }
            }
        };
        return (
            <Layout>
                <Header className="header" style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    color: "#fff",
                    padding: "0"
                }}>
                    <div
                        className="logo"
                        style={{
                            flex: "none",
                            width: this.state.collapsed ? "60px" : "200px",
                            borderRight: "1px solid rgb(99, 99, 99)",
                            textAlign: "center",
                            fontSize: "22px",
                            cursor: "pointer"
                        }}
                        onClick={() => { this.setState({ collapsed: !this.state.collapsed }); }}
                    >
                        {this.state.collapsed ? <Icon type="setting" /> : <span style={{ textShadow: "1px 1px 5px #fff" }}>React 最小系统</span>}
                    </div>
                    <div className="nav_title" style={{
                        flex: "1",
                        padding: "0 20px",
                    }}>
                        <span
                            style={{ fontSize: "18px", color: "#fff", marginRight: "8px" }}
                            onClick={() => { this.setState({ collapsed: !this.state.collapsed }); }}
                        >
                            {this.state.collapsed ? <Icon type="appstore" /> : <Icon type="bars" />}
                        </span>
                        {this.props.historyroute.map((item, index) => (
                            <Tag
                                key={item.path}
                                closable={index !== this.props.historyroute.length - 1}
                                color={(index === this.props.historyroute.length - 1) ? "#c1c1c166" : "#58585833"}
                                onClose={() => { this.spliceTag(index); }}
                                onClick={e => { this.clickTag(e.target, item.path, index); }}
                            >{item.name}</Tag>
                        ))}
                    </div>
                    <Dropdown overlay={<Menu>
                        <Menu.Item onClick={() => { window.location.hash = "/main"; }}>控制台</Menu.Item>
                        <Menu.Item onClick={() => { window.location.hash = "/setup"; }}>设置</Menu.Item>
                        <Menu.Divider />
                        <Menu.Item onClick={() => { this.logout(); }}>退出登录</Menu.Item>
                    </Menu>}>
                        <div className="userinfo" style={{
                            flex: "none",
                            paddingRight: "30px",
                            cursor: "default"
                        }}>
                            <img alt={this.props.userinfo.ZK_NAME} src={this.props.userinfo.ZK_HEAD_PORTRAIT} style={{
                                height: "40px",
                                width: "40px",
                                borderRadius: "50%",
                                marginRight: "8px"
                            }} />
                            <strong>{this.props.userinfo.ZK_NAME}</strong>
                        </div>
                    </Dropdown>
                </Header>
                <Layout style={{ minHeight: "calc(100vh - 64px)" }}>
                    <Sider width={this.state.collapsed ? 60 : 200} style={{ background: '#fff' }}>
                        {createMemu()}
                    </Sider>
                    <Layout style={{ padding: '0 24px 24px' }}>
                        <Breadcrumb style={{ margin: '12px 0' }}>
                            {this.state.breadcrumbs.map(item => (
                                <Breadcrumb.Item key={item}>{item}</Breadcrumb.Item>
                            ))}
                        </Breadcrumb>
                        <Router>
                            <Content style={{ background: '#fff', padding: 24, margin: 0, minHeight: 480 }}>
                                {this.props.source.map(item => (
                                    <Route exact path={item.path} component={item.component} key={item.path} />
                                ))}
                            </Content>
                        </Router>
                    </Layout>
                </Layout>
            </Layout>
        );
    }
}

export default connect(store => {
    return {
        userinfo: store.userinfo,
        historyroute: store.historyroute
    }
})(Home);